
from elasticsearch import Elasticsearch

# 1. 连接Elasticsearch集群
es = Elasticsearch(
    hosts=["http://localhost:9200"],
    basic_auth=('elastic', 'your_password'),  # 若未启用安全认证可省略
    sniff_on_start=True,
    sniff_on_connection_fail=True,
    sniff_timeout=60,
    ignore=[400, 404]  # 忽略索引不存在等错误
)

# 2. 创建索引（带分片配置）
if not es.indices.exists(index="news"):
    es.indices.create(
        index="news",
        body={
            "settings": {
                "number_of_shards": 3,
                "number_of_replicas": 1
            }
        },
        ignore=400
    )

# 3. 文档操作示例
# 插入文档
doc1 = {
    "title": "Python连接ES教程",
    "content": "详细讲解Python客户端使用方法",
    "tags": ["python", "elasticsearch"],
    "view_count": 150
}
res = es.index(index="news", id=1, body=doc1)
print(f"文档插入结果: {res['result']}")

# 查询文档
query = {
    "query": {
        "bool": {
            "must": [
                {"match": {"content": "客户端"}},
                {"range": {"view_count": {"gte": 100}}}
            ]
        }
    },
    "sort": [{"view_count": {"order": "desc"}}]
}
results = es.search(index="news", body=query)
print(f"查询到 {results['hits']['total']['value']} 条结果")

# 更新文档
update_body = {
    "doc": {
        "view_count": 200,
        "tags": ["python", "elasticsearch", "database"]
    }
}
es.update(index="news", id=1, body=update_body)

# 删除文档
es.delete(index="news", id=1)

# 4. 批量操作
from elasticsearch.helpers import bulk
actions = [
    {"_index": "news", "_id": 2, "_source": {"title": "批量插入1", "category": "技术"}},
    {"_index": "news", "_id": 3, "_source": {"title": "批量插入2", "category": "新闻"}}
]
bulk(es, actions)
